package com.yanqu.road.dataHelper.action.excel;

import com.yanqu.road.dataHelper.gameServer.GameServer;
import com.yanqu.road.dataHelper.repair.BaseRepair;
import com.yanqu.road.entity.log.LogLogin;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class UserOnlineTimeDetail extends BaseRepair {

    public UserOnlineTimeDetail(GameServer gameServer) {
        super(gameServer);
    }

    public void go(FileWriter writer) throws IOException {
        List<UserInfo> userList = selectAllUser();
        for (UserInfo info : userList) {
            List<LoginDetail> loginDetails = selectUserLoginLog(info.getUserId());
            loginDetails.sort(new Comparator<LoginDetail>() {
                @Override
                public int compare(LoginDetail o1, LoginDetail o2) {
                    return Long.compare(o1.getTime(),o2.getTime());
                }
            });

            long lastLoginTime = 0 ;
            boolean resetLoginTime = true;
            Map<String, Long> dateOnlineMap = new TreeMap<>();
            for (LoginDetail detail : loginDetails) {
                int type = detail.getType();
                if (type == 0) {
                    if (resetLoginTime) {
                        lastLoginTime = detail.getTime();
                        resetLoginTime = false;
                    }
                } else if (type == 1) {
                    resetLoginTime = true;
                    if (lastLoginTime != 0) {
                        long onlineTime = detail.getTime() - lastLoginTime;
                        Date date = new Date(lastLoginTime);
                        String format = new SimpleDateFormat("yyyy-MM-dd").format(date);
                        Long orDefault = dateOnlineMap.getOrDefault(format, 0L);
                        dateOnlineMap.put(format, orDefault + onlineTime);
                    }
                }
            }
            for (Map.Entry<String, Long> entry : dateOnlineMap.entrySet()) {
                String dateMark = entry.getKey();
                Long onlineTime = entry.getValue()/1000;
                String s = info.getUserId() + "       " + dateMark + "        " + onlineTime + "\n";
                System.out.println(s);
                writer.write(s);
            }
            writer.flush();
        }
    }

    private  List<LoginDetail> selectUserLoginLog(long userId) {
        List<LoginDetail> dataList = new ArrayList<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "SELECT userId,time,type FROM t_l_login where userId = ?";
        try {
            call = getGameServer().getLogConnection().prepareCall(sql);
            call.setLong(1, userId);
            rs = call.executeQuery();
            while (rs.next()) {
                LoginDetail logLogin = new LoginDetail();
                logLogin.setUserId(rs.getLong("userId"));
                logLogin.setTime(rs.getTimestamp("time").getTime());
                logLogin.setType(rs.getInt("type"));
                dataList.add(logLogin);
            }
        } catch (SQLException ex) {
            getGameServer().getLogger().error("异常错误", ex);
        } finally {
            getGameServer().closeConnection(call, rs);
        }
        return dataList;
    }

    private List<UserInfo> selectAllUser() {
        List<UserInfo> dataList = new ArrayList<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "SELECT userId,titleId,registerTime,nickName,vipExp,sex,earnSpeed,phonePlatform FROM t_u_user";
        try {
            call = getGameServer().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                String nickName = rs.getString("nickName");
                if (StringUtils.isNullOrEmpty(nickName)) {
                    continue;
                }
                UserInfo userInfo = new UserInfo();
                userInfo.setUserId(rs.getLong("userId"));
                userInfo.setRegisterTime(rs.getLong("registerTime"));
                userInfo.setVipExp(rs.getInt("vipExp"));
                dataList.add(userInfo);
            }
        } catch (SQLException ex) {
            getGameServer().getLogger().error("异常错误", ex);
        } finally {
            getGameServer().closeConnection(call, rs);
        }
        return dataList;
    }
    @Override
    public void repair(long param1, String param2) {

    }
}
